package com.ruoyi.web.controller.wechatpublic;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.WechatMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@RestController
@RequestMapping("/wechat/publicAccount")
public class WechatPublicAccountController{

    @Autowired
    WechatMsg wechatMsg;

    // 微信页面填写的token，必须保密
    @Value("${token.header}")
    private String TOKEN;

    @GetMapping("/validate")
    public String validate(HttpServletRequest request, HttpServletResponse response) {
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String signature = request.getParameter("signature");
        String echostr = request.getParameter("echostr");
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = {timestamp, nonce, TOKEN};
        Arrays.sort(arr);
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder sb = new StringBuilder();
        for (String temp : arr) {
            sb.append(temp);
        }
        // 这里利用了hutool的加密工具类
        String sha1 = SecureUtil.sha1(sb.toString());
        // 3. 加密后的字符串与signature对比，如果相同则该请求来源于微信，原样返回echostr
        if (sha1.equals(signature)) {
            return echostr;
        }
        // 接入失败
        return null;
    }

    /**
     * 群发消息
     * @param
     * @return
     */
    @RequestMapping(value="/groupMessage",method= RequestMethod.POST,produces ="application/json;charset=utf-8")
    public JSONObject Message(@RequestBody(required=false)JSONObject obje) {
        JSONObject result=new JSONObject();
        String content=obje.getString("content");//群发内容
        Integer code=wechatMsg.GroupMessage(wechatMsg.getToken(),content);//群发消息
        if(code==0) {
            result.put("code",0);
            result.put("data","群发成功");
        }else {
            result.put("code",1201);
            result.put("data","微信群发消息失败");
        }
        return result;
    }
}

